function changeState(id, state) {
    $.ajax({
        type: 'POST',
        url: "changeState",
        data: {
            id: id,
            state: state
        },
        success: function () {
            $('#mytable').bootstrapTable('refresh', {url: '/admin/fenxiaofan/list'});
        },
        dataType: "json"
    });
}

function deleteOne(id) {
    swal({
        title: '您确定要删除此行数据？',
        text: '你将无法恢复它！',
        type: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#ed5666',
        confirmButtonText: '确定删除！',
        cancelButtonText: '取消删除！',
        confirmButtonClass: 'btn btn-success',
        cancelButtonClass: 'btn btn-danger',
        buttonsStyling: false
    }).then(function () {

        $.ajax({
            type: 'POST',
            url: "deleteOne",
            data: {
                id: id,
            },
            success: function (status) {
                if (status == 1) {
                    swal({title: "删除成功", text: "", type: "success"})
                    $("#hidleftlevel").val(parseInt($("#hidleftlevel").val() - 1))
                    // initSaveDiv();
                    // $('#mytable').bootstrapTable('refresh', {url: '/admin/fenxiaofan/list'});
                    window.location.reload();
                } else {
                    swal({title: "删除失败", text: "", type: "error"})
                }
            },
            dataType: "json"
        });

    }, function (dismiss) {
        // dismiss的值可以是'cancel', 'overlay',
        // 'close', 'timer'
        if (dismiss === 'cancel') {
            swal({title: '您已取消操作！', text: '', timer: 2000})
        }
    })
}

function changeLevel() {

}

var editsw = [];

/**
 * 为模态框填充数据
 */
$('#modal-form').on('show.bs.modal', function (event) {
    var button = $(event.relatedTarget); // 触发事件的按钮
    var index = button.data('index');
    var modal = $(this);
    var data = $('#mytable').bootstrapTable("getData")[index]
    console.log(data)

    modal.find('#id').val(data.id)

    // modal.find('#hytype').find("option[value='" + data['hytype'] + "']").attr("selected", true);
    // modal.find('#mlevel').find("option[value='" + data['mlevel'] + "']").attr("selected", true);
    // modal.find('#thytype').find("option[value='" + data['thytype'] + "']").attr("selected", true);
    // modal.find('#tlevel').find("option[value='" + data['tlevel'] + "']").attr("selected", true);
    mfxlevelChange(data.mlevel)

    editsw["isJiandian"] == undefined ? editsw["isJiandian"] = new Switchery(document.querySelector('#isJiandian'), {color: "#1AB394"}) : ""
    console.log("======switchery")
    console.log(editsw["isJiandian"])
    if (data.isJiandian == 1) {
        setSwitchery(editsw["isJiandian"], true);
    } else {
        setSwitchery(editsw["isJiandian"], false);
    }

    modal.find('#mzhekou').val(data.mzhekou)
    modal.find('#fan1').val(data.fan1)
    modal.find('#xffan1').val(data.xffan1)
    modal.find('#fan2').val(data.fan2)
    modal.find('#xffan2').val(data.xffan2)
    modal.find('#fan3').val(data.fan3)
    modal.find('#xffan3').val(data.xffan3)
    modal.find('#fan4').val(data.fan4)
    modal.find('#xffan4').val(data.xffan4)
    modal.find('#fan5').val(data.fan5)
    modal.find('#xffan5').val(data.xffan5)
    modal.find('#fan6').val(data.fan6)
    modal.find('#xffan6').val(data.xffan6)
    modal.find('#fan7').val(data.fan7)
    modal.find('#xffan7').val(data.xffan7)

})

//tableHeight函数
function tableHeight() {
    //可以根据自己页面情况进行调整
    return $(window).height() - 200;
}

function ahytypeChange(hytype, target, hid) {
    //可以根据自己页面情况进行调整
    $.ajax({
        type: 'POST',
        url: "getLeftLevel",
        data: {
            hytype: hytype,
        },
        success: function (e) {
            if (e.code == 0 && e.data) {
                $("#" + target).empty();
                e.data.forEach(function (item, index) {
                    console.log("--------ahytypeChange index=" + index)
                    var option = $("<option>").val(item.code).text(item.msg);
                    $("#" + target).append(option)
                    if (index == 0) $("#" + hid).val(item.msg);
                })
            }
        },
        dataType: "json"
    });
}


function athytypeChange(hytype, target, hid) {
    //可以根据自己页面情况进行调整
    $.ajax({
        type: 'POST',
        url: "getTuiLeftLevel",
        data: {
            hytype: hytype,
        },
        success: function (e) {
            if (e.code == 0 && e.data) {
                $("#" + target).empty();
                e.data.forEach(function (item, index) {
                    console.log("----------------athytypeChange index=" + index)
                    var option = $("<option>").val(item.code).text(item.msg);
                    $("#" + target).append(option)
                    if (index == 0) $("#" + hid).val(item.msg);
                })
            }
        },
        dataType: "json"
    });
}

function afxlevelChange(level) {
    $("#hidmname").val($("#mlevel option:selected").text());
    console.log("-------afxlevelChange")
    console.log($("#mlevel option:selected").text())
    console.log($("#hidmname").val())
    // var level = level || $("#thytype2 option:selected").val();
    // console.log(level)
    // for (var i = 1; i <= 7; i++) {
    //     if (i <= level) $("#arow" + i).show()
    //     else $("#arow" + i).hide()
    // }
}

function atfxlevelChange(level) {
    $("#hidtname").val($("#tlevel option:selected").text());
    console.log("-------atfxlevelChange")
    console.log($("#tlevel option:selected").text())
    console.log($("#hidtname").val())
    // var level = level || $("#fxlevel2 option:selected").val();
    // console.log(level)
    // for (var i = 1; i <= 7; i++) {
    //     if (i <= level) $("#arow" + i).show()
    //     else $("#arow" + i).hide()
    // }
}

function mfxlevelChange(level) {
    var level = level || $("#fxlevel2 option:selected").val();
    console.log(level)
    for (var i = 1; i <= 7; i++) {
        if (i <= level) $("#mrow" + i).show()
        else $("#mrow" + i).hide()
    }
}

function initSaveDiv() {
    if ($("#hidleftlevel").val() > 0) {
        $("#saveDiv").show()
    } else {
        // $("#saveDiv").hide()
    }
    // if ($("#hidleftlevel").val() >= 0) {
    //     $("#tablediv").show()
    // } else {
    //     $("#tablediv").hide()
    // }
}

function actFormatter(value, row, index) {
    var state = row.state;
    var id = row.id;
    var res = '<button data-toggle="modal" class="btn-sm btn-primary" href="list.html#modal-form" data-row=' + id + ' data-index=' + index + '>修改</button>';
    res += ' <button typ-e="button" class="btn-sm btn-danger" onclick="deleteOne(\'' + id + '\')">删除</button>';
    return res;
}

var fanyongs = [[{
    title: '一级返佣',
    field: 'fan1'
},
    {
        title: '一级消费返点',
        field: 'xffan1'
    }],
    [{
        title: '二级返点',
        field: 'fan2'
    },
        {
            title: '二级消费返点',
            field: 'xffan2'
        }],
    [{
        title: '三级返点',
        field: 'fan3'
    },
        {
            title: '三级消费返点',
            field: 'xffan3'
        }],
    [{
        title: '四级返点',
        field: 'fan4'
    },
        {
            title: '四级消费返点',
            field: 'xffan4'
        }],
    [{
        title: '五级返点',
        field: 'fan5'
    },
        {
            title: '五级消费返点',
            field: 'xffan5'
        }],
    [{
        title: '六级返点',
        field: 'fan6'
    },
        {
            title: '六级消费返点',
            field: 'xffan6'
        }],
    [{
        title: '七级返点',
        field: 'fan7'
    },
        {
            title: '七级消费返点',
            field: 'xffan7'
        }]];
var columns = [
    {
        title: '全选',
        field: 'select',
        checkbox: true,
        width: 25,
        align: 'center',
        valign: 'middle'
    },
    {
        title: 'ID',
        field: 'id',
        visible: false
    },
    {
        title: '会员名称',
        field: 'mname'
    },
    {
        title: '会员级别',
        field: 'mlevel'
    },
    {
        title: '推荐会员名称',
        field: 'tname'
    },
    {
        title: '推荐会员级别',
        field: 'tlevel'
    }]
var acts = [
    {
        title: '操作',
        field: 'Attribute',
        align: 'center',
        width: 170,
        formatter: actFormatter
    }];

function initColumns() {
    var level = $("#hidfxlevel").val();
    for (var i = 1; i <= level; i++) {
        columns.push(fanyongs[i - 1][0])
        columns.push(fanyongs[i - 1][1])
    }
    columns.push(acts[0])
    columns.push(acts[1])
    return columns;
}

$(function () {

    var sw = [];
    $(".js-switch").each(function (i, e) {
        sw[i] = new Switchery(e, {color: "#1AB394"})
    })
    $(window).resize(function () {
        $('#mytable').bootstrapTable('resetView', {
            height: tableHeight()
        })
    })
    console.log("======init to hide arow")
    // var curlevel = $("#mlevel2 option:selected").val();
    var curlevel = $("#mlevel2 option:selected").val() || $("#hidfxlevel").val();
    console.log("======curlevel=" + curlevel)
    for (var i = 1; i <= 7; i++) {
        console.log("======init to hide arow i=" + i)
        if (i > curlevel) $("#arow" + i).hide()
        // $("#mrow"+i).hide()
    }
    initSaveDiv();
    //生成用户数据
    $('#mytable').bootstrapTable({
        method: 'get',
        url: "/admin/fenxiaofan/list",
        // height:520,//高度调整
        // toolbar: '#toolbar',
        striped: true, //是否显示行间隔色
        dataField: "records",
        pagination: true,//是否分页
        queryParamsType: 'limit',
        queryParams: queryParams,
        sidePagination: 'server',
        pageNumber: 1, //初始化加载第一页，默认第一页
        pageSize: 50,//单页记录数
        pageList: [50, 100, 200, 500],//分页步进值
        showExport: true,//显示导出
        showRefresh: false,//刷新按钮
        showColumns: false,
        clikToSelect: true,//是否启用点击选中行
        // toolbarAlign:'right',
        // buttonsAlign:'right',//按钮对齐方式
        columns: initColumns(),
        locale: 'zh-CN',//中文支持,
    })

    //请求服务数据时所传参数
    function queryParams(params) {
        var p = {
            limit: params.limit,
            offset: params.offset,
            sort: params.sort,
            order: params.order
            , search: $('#search').val() || ""
            , status: $('#qstatus').val() || 99
        }
        return p;
    }

    $('#search_btn').click(function () {
        var p = {
            status: $('#qstatus').val(),
            search: $('#search').val(),
            ts: new Date().getTime()
        };
        $('#mytable').bootstrapTable('refresh', p);
    })

    /*
     * 验证错误提示信息高亮
     */
    $.validator.setDefaults({
        highlight: function (e) {
            $(e).closest(".form-group").removeClass("has-success").addClass("has-error")
        }, success: function (e) {
            e.closest(".form-group").removeClass("has-error").addClass("has-success")
        }, errorElement: "span", errorPlacement: function (e, r) {
            e.appendTo(r.is(":radio") || r.is(":checkbox") ? r.parent().parent().parent() : r.parent())
        }, errorClass: "help-block m-b-none", validClass: "help-block m-b-none"
    }), $("#aform").validate(), $("#mform").validate();
})

function checkAdd() {
    $('input:checkbox').each(function (index, item) {
        if ($(this).prop("checked")) {
            $(this).val(1);
            console.log($(this).attr("name") + "=" + $(this).val())
        } else {
            $(this).val(-1);
            console.log($(this).attr("name") + "=" + $(this).val())
        }
    });
    $('input:number').each(function (index, item) {
        if ($(this).attr("name").indexOf('fan') == 0) {
            if ($(this).val() == '' || $(this).val() < 0 || $(this).val() > 100) {
                swal({title: "分销设置提示", text: "返佣比例必须在0~100之间", type: "error"})
                return;
            }
        }
        if ($(this).attr("name").indexOf('xffan') == 0) {
            if ($(this).val() == '' || $(this).val() < 0 || $(this).val() > 100) {
                swal({title: "分销设置提示", text: "消费返点比例必须在0~100之间", type: "error"})
                return;
            }
        }
    });
    $("#mname").val($("#fxlevel2 option:selected").text());
    console.log("======mname")
    console.log($("#mname").val())

    return true;
}

function checkModify() {
    $('input:checkbox').each(function (index, item) {
        if ($(this).prop("checked")) {
            $(this).val(1);
            console.log($(this).attr("id") + "=" + $(this).val())
        } else {
            $(this).val(-1);
            console.log($(this).attr("id") + "=" + $(this).val())
        }
    });
    $('input:text').each(function (index, item) {
        if ($(this).attr("name").indexOf('fan') == 0) {
            if ($(this).val() == '' || $(this).val() < 0 || $(this).val() > 100) {
                swal({title: "分销设置提示", text: "返佣比例必须在0~100之间", type: "error"})
                return;
            }
        }
        if ($(this).attr("name").indexOf('xffan') == 0) {
            if ($(this).val() == '' || $(this).val() < 0 || $(this).val() > 100) {
                swal({title: "分销设置提示", text: "消费返点比例必须在0~100之间", type: "error"})
                return;
            }
        }
    });

    return true;
}